<script setup>
import { ref,watch ,onMounted} from 'vue';
import {queryClazzApi,addClazzApi,queryClazzByIdApi,updateClazzApi,delClazzByIdApi} from '../../api/clazz'
import {findAllMaster} from '../../api/emp'
import { ElMessage, ElMessageBox } from 'element-plus';

// 查询栏
const searchClazz = ref({name:'',date:[],begin:'',end:''})

// 元数据
const subjects = ref([{name:'Java',value:'1'},{name:'前端',value:'2'},{name:'大数据',value:'3'},{name:'Python',value:'4'},{name:'Go',value:'5'},{name:'嵌入式',value:'6'}])

// 加载班主任数据
onMounted(async () => {
  const result = await findAllMaster()
  if(result.code){
    masters.value = result.data
  }
})

// 查询全部班主任
const masters = ref([])

// 钩子函数
onMounted(() => {
  search()
})

// 查询按钮
const search = async () =>{
  const result = await queryClazzApi(searchClazz.value.name,searchClazz.value.begin,searchClazz.value.end,
                                currentPage.value,pageSize.value)
  if(result.code){
    clazzsList.value = result.data.rows
    total.value = result.data.total
  }
}
// watch侦听，将date[] 的数据赋值给begin 和 end
watch( ()=>{return searchClazz.value.date} , (newValue,oldValue) => {
    if(newValue.length == 2){
      searchClazz.value.begin = newValue[0]
      searchClazz.value.end = newValue[1]
    }else{
      searchClazz.value.begin = ''
      searchClazz.value.end = ''
    }
  }
)
// 清空按钮
const clear = () => {
  searchClazz.value = {name:'',date:[],begin:'',end:''}
  search()
}

// dailog对话框
const dialogFormVisible = ref(false)
const FormTitle = ref('新增班级')

// 班级对象信息
const clazz = ref({
  name:'',
  room:'',
  beginDate:'',
  endDate:'',
  masterId:'',
  subject:''
})

// 新增班级
const addClazz = () =>{
  dialogFormVisible.value = true
  FormTitle.value = '新增班级'
  clazz.value = {
    name:'',
    room:'',
    beginDate:'',
    endDate:'',
    masterId:'',
    subject:''
  }
  // 清除校验
   if(clazzFormRef.value){
    clazzFormRef.value.resetFields()
  }
}
//保存数据
const save = () => {
  clazzFormRef.value.validate( async (valid) => {
    if(valid) { //校验通过
      let result
      if(clazz.value.id){
        result = await updateClazzApi(clazz.value)
      }else{
        result = await addClazzApi(clazz.value)
      }
      if(result.code){
        ElMessage.success('操作成功')  
        dialogFormVisible.value = false
        search()
      }else{
        ElMessage.error(result.msg)
      }
    }else{  //校验不通过
      ElMessage.error('表单校验不通过')
    }
  })
}

// 数据输入时校验
const rules = ref({
  name: [
    { required: true, message: '班级名称为必填项', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称长度应在4到30个字符之间', trigger: 'blur' }
  ],
  beginDate:[
    { required: true, message: '开课时间为必填项', trigger: 'blur' },
  ],
  endDate:[
    { required: true, message: '结课时间为必填项', trigger: 'blur' },
  ],
  subject:[
    { required: true, message: '学科为必填项', trigger: 'blur' },
  ]
});

// 数据提交时校验
const clazzFormRef = ref()


// 表格数据
const clazzsList = ref([])

// 分页条数据
const currentPage = ref(1) // 展示第几页
const pageSize = ref(10)  // 每页展示多少条数据
const background = ref(true) // 背景色
const total = ref(0) //总记录数
// 分页查询
const handleSizeChange = () => {
  search()
}
const handleCurrentChange = () => {
  search()  
}

// 编辑信息
// 1.查询回显  2.提交数据
const edit = async (id) => {
  console.log(`返回回来的id为：${id}`);
  const result = await queryClazzByIdApi(id)
  if(result.code){
    dialogFormVisible.value = true
    FormTitle.value = '编辑信息'
    clazz.value = result.data
    if(clazz.value.subject !== null && clazz.value.subject !== undefined){
      clazz.value.subject = clazz.value.subject.toString()
    }
  }
}

// 删除信息
const del = async (id) => {
  ElMessageBox.confirm('您确定要删除信息吗？','提示',
    {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
  ).then( async() => {  //确认删除
    const result = await delClazzByIdApi(id)
    if(result.code){
      ElMessage.success('操作成功')
      search()
    }else{
      ElMessage.error(result.msg)
    }
  }).catch(() => {  // 取消删除
      ElMessage.info('您已取消删除')
  });
}

</script>

<template>
  <div class="">
    <h1>班级管理</h1>
  </div>
  <!-- 查询栏 -->
  <div class="style">
  <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
    <el-form-item label="班级名称">
      <el-input v-model="searchClazz.name" placeholder="请输入班级名"  />
    </el-form-item>
    <el-form-item label="结课时间">
      <el-date-picker
        v-model="searchClazz.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
</div>

  <!-- 按钮 -->
  <div class="style">
    <el-button type="success" @click="addClazz">+ 新增班级</el-button>
  </div>

  <!-- 表格 -->
  <div class="style">
    <el-table :data="clazzsList" border style="width: 100%">
    <el-table-column type="index" prop="id" label="序号" width="100"  align="center"/>
    <el-table-column prop="name" label="班级名称" width="200" align="center"/>
    <el-table-column prop="room" label="班级教室" width="100" align="center"/>
    <el-table-column prop="masterName" label="班主任" width="100" align="center"/>
    <el-table-column prop="beginDate" label="开课时间" width="120" align="center"/>
    <el-table-column prop="endDate" label="结课时间" width="120" align="center"/>
    <el-table-column prop="status" label="状态" width="100" align="center"/>
    <el-table-column prop="updateTime" label="最后修改时间" width="300"align="center"/>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  </div>

   <!-- 分页条 -->
  <div class="style">
    <el-pagination
      v-model:current-page="currentPage"  
      v-model:page-size="pageSize"
      :page-sizes="[5,10, 20, 50, 100]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- dialog弹框 -->
  <el-dialog v-model="dialogFormVisible" :title="FormTitle" width="500" >
      <el-form :model="clazz" :rules="rules" ref="clazzFormRef" >
        <el-form-item label="班级名称 " label-width="80px" prop="name">
          <el-input v-model="clazz.name" placeholder="请输入班级名称"/>
        </el-form-item>
        <el-form-item label="班级教室" label-width="80px" >
          <el-input v-model="clazz.room"  placeholder="请输入班级教室"/>
        </el-form-item>
        <el-form-item label="开课时间" label-width="80px" prop="beginDate">
          <el-date-picker v-model="clazz.beginDate" type="date" style="width: 100%;" placeholder="请选择开课时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="结课时间" label-width="80px" prop="endDate">
          <el-date-picker v-model="clazz.endDate" type="date" style="width: 100%;" placeholder="请选择结课时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="班主任" label-width="80px" prop="">
          <el-select v-model="clazz.masterId" placeholder="请选择班主任" style="width: 100%;">
              <el-option v-for=" m in masters" :key="m.id" :label="m.name" :value="m.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学科" label-width="80px" prop="subject">
          <el-select v-model="clazz.subject" placeholder="请选择学科" style="width: 100%;">
              <el-option v-for=" s in subjects" :key="s.value" :label="s.name" :value="s.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>






</template>

<style scoped>
.style{
  margin: 15px;
}

</style>